package Game;
import java.io.*;

/*
 * William Kurkian
 * THis class saves the game, loads it, and checks if a save exists through java object serialization.
 * Only one save file can currently be held at a time, which is saves/current.data
 */
public class GameSave {

	String folder = System.getProperty("user.dir")+File.separator+"saves"+File.separator;
	String file = "current.data";
	
	/**
	 * Saves the passed in game driver
	 * @param gd the GameDriver to save.
	 * @return
	 */
	public String saveGame(GameDriver gd) {
	
		try {
			FileOutputStream f_out = new 
				FileOutputStream(folder + file);
		
			// Write object with ObjectOutputStream
			ObjectOutputStream obj_out = new
				ObjectOutputStream (f_out);
		
			// Write object out to disk
			obj_out.writeObject ( gd );
			obj_out.close();
			f_out.close();
		} catch (Exception e) {
			return e.getMessage();
		}
		return "Save Successful";
	}
	/**
	 * Loads the save with object serialization.
	 * @return the saved game driver
	 */
	public GameDriver loadGame() {
		try {
			// Read from disk using FileInputStream
			FileInputStream f_in = new 
				FileInputStream(folder + file);

			// Read object using ObjectInputStream
			ObjectInputStream obj_in = 
				new ObjectInputStream (f_in);

			// Read an object
			Object obj = obj_in.readObject();

			GameDriver gd = (GameDriver)obj;
			obj_in.close();
			f_in.close();
			return gd;
		}catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return null;
	}
	
	/**
	 * Returns whether the save exists.
	 * @return whether a save exists.
	 */
	public boolean saveExists() {
		try {
			// Read from disk using FileInputStream
			FileInputStream f_in = new 
				FileInputStream(folder + file);

			// Read object using ObjectInputStream
			ObjectInputStream obj_in = 
				new ObjectInputStream (f_in);

			// Read an object
			Object obj = obj_in.readObject();

			GameDriver gd = (GameDriver)obj;
			obj_in.close();
			f_in.close();
			
		}catch (Exception e) {
			System.out.println(e.getMessage());
			return false;
		}
		return true;

	}
}
